<template>
  <div class="container">
    <el-card>
      <template #header>
        <el-button type="primary" :icon="Plus" @click="onShowDialog">添加</el-button>
      </template>
      <el-table :data="state.trademarkList" border style="width: 100%" stripe>
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="tmName" label="品牌名称" width="180" />
        <el-table-column prop="name" label="品牌log" width="180">
          <template #default="{ row }">
            <img class="logoUrl" :src="row.logoUrl" alt="" />
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <!-- 必须给 template 写上插槽的名字-->
          <template #default="{ row }">
            <el-button type="warning" size="small" :icon="Edit" @click="onShowEdit(row.id)"
              >修改</el-button
            >
            <el-button type="danger" size="small" :icon="Delete" @click="delTrademark(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="state.page"
        v-model:page-size="state.limit"
        :page-sizes="[10, 15, 20, 25]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="state.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog
      v-model="showDialog"
      :title="isEdit ? '编辑品牌' : '新增品牌'"
      width="50%"
      :before-close="handleClose"
    >
      <el-form ref="fromRef" :rules="rules" :model="formData" label-width="90px">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="formData.tmName" />
        </el-form-item>
        <el-form-item label="品牌Logo" prop="logoUrl">
          <!-- upload 上传组件 -->
          <!-- action 上传地址 -->
          <!-- show-file-list 是否显示已上传文件列表 -->
          <!-- on-success 图片上传成功以后的逻辑 -->
          <!-- before-upload 上传之前 -->
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData.logoUrl" :src="formData.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelHandler">取消</el-button>
          <el-button type="primary" @click="confirmHandler">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'

import {
  baseTrademark,
  reqTrademark,
  reqAddTrademark,
  reqUpdateTrademark,
  reqRemoveTrademark
} from '@/api/Trademark'
import type { ITrademarkState, Record } from '@/types/trademark'

import type { UploadProps, FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
//#region
//弹窗的title值
const isEdit = ref(false)
//表单引用对象
const fromRef = ref<FormInstance>()
//弹窗输入框格式
const rules = ref({
  tmName: [{ required: true, message: '输入品牌名称', tigger: 'blur' }],
  logoUrl: [{ required: true, message: '添加图片', tigger: 'change' }]
})
// 控制弹框的隐藏与展示
const showDialog = ref(false)
// 新增和编辑功能需要收集的数据
const formData = ref({
  tmName: '', // 品牌 名字
  logoUrl: '' // 品牌 Logo
})
//编辑id
const tId = ref<number>()
// 拼接上传的地址
const uploadUrl = import.meta.env.VITE_API_URL + '/admin/product/upload'

// 上传成功的回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // formData.value.logoUrl = URL.createObjectURL(uploadFile.raw!)
  // console.log(response.data)

  // console.log(URL.createObjectURL(uploadFile.raw!))
  formData.value.logoUrl = response.data
  // 如果验证通过，会将错误提示清除，如果验证没有通过，错误提示依然存在
  fromRef.value?.validateField('logoUrl')
}

// 分页初始化数据
// 上传之前的逻辑
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片格式必须是 jpeg 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传的图片体积不能大于 2MB!')
    return false
  }
  return true
}

// 新增品牌按钮
const onShowDialog = () => {
  isEdit.value = false
  showDialog.value = true
}

//编辑品牌按钮
const onShowEdit = async (id: number) => {
  isEdit.value = true
  showDialog.value = true
  const res = await reqTrademark(id)
  tId.value = id
  console.log(tId.value)

  if (res.code === 200) {
    formData.value.tmName = res.data.tmName
    formData.value.logoUrl = res.data.logoUrl
  }
}
// 新增和编辑弹框确定按钮
const confirmHandler = async () => {
  await fromRef.value?.validate()
  const res = isEdit.value
    ? await reqUpdateTrademark({ id: tId.value, ...formData.value })
    : await reqAddTrademark(formData.value)
  if (res.code === 200) {
    cancelHandler()
    ElMessage({
      type: 'success',
      message: isEdit.value ? '修改成功' : '添加成功',
      duration: 4000
    })
    getTrademark()
  } else {
    ElMessage({
      type: 'error',
      message: res.message || 'error',
      duration: 4000
    })
  }
}
//删除功能
const delTrademark = async (row: Record) => {
  ElMessageBox.confirm(`您确定要删除 ${row.tmName} 吗？`, '删除提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await reqRemoveTrademark(row.id)

      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })

        getTrademark()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
// 新增和编辑弹框取消按钮
const cancelHandler = () => {
  showDialog.value = false

  // formData.value.logoUrl = ''
  // formData.value.tmName = ''
  fromRef.value?.resetFields()
}

// 新增和编辑弹框关闭之前
const handleClose = () => {
  cancelHandler()
}

//#endregion
//#region
// 分页初始化数据
const state: ITrademarkState = reactive({
  page: 1,
  limit: 10,
  total: 0,
  trademarkList: []
})

//获取品牌列表
const getTrademark = async () => {
  const res = await baseTrademark(state.page, state.limit)
  console.log(res)

  if (res.code === 200) {
    state.total = res.data.total
    state.trademarkList = res.data.records
  }
}

onMounted(() => {
  getTrademark()
})

// page-size 改变时触发
const handleSizeChange = (value: number) => {
  // #Todo
  state.limit = value
  getTrademark()
}

// current-page 改变时触发
const handleCurrentChange = (value: number) => {
  // #Todo
  state.page = value
  getTrademark()
}

//#endregion
</script>

<script lang="ts">
export default {
  name: 'VTrademark'
}
</script>

<style lang="scss" scoped>
.container {
  margin-top: 20px;
}

.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.logoUrl {
  width: 100px;
}
.avatar-uploader .avatar {
  width: 175px;
  height: 175px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
